/*
 * Copyright (c)  2018, XiQiao
 * All rights reserved. 
 *
 * Id:DateUtils.java   2018-07-26 23:15 wanglijun
 */
package io.marmot.poi.util;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2018
 * </p>
 * <p>
 * Company: XiQiao
 * </p>
 *
 * @author: wanglijun
 * @create: 2018-07-26 23:15
 * @version：1.0
 */
public class DateUtils {

    public final static SimpleDateFormat ENGLISH_LOCAL_DF = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    private final static LoadingCache<String, SimpleDateFormat> DATE_FORMAT_LOADING_CACHE =
            CacheBuilder.newBuilder()
                    .maximumSize(5)
                    .build(new CacheLoader<String, SimpleDateFormat> () {

                        @Override
                        public SimpleDateFormat load(String pattern) {
                            return new SimpleDateFormat(pattern);
                        }
                    });

    public static Date parse(String pattern, Object value) throws Exception {
        String valueString = (String) value;
        return DATE_FORMAT_LOADING_CACHE.get(pattern).parse(valueString);
    }

    public static String format(String pattern, Date value) {
        try {
            return DATE_FORMAT_LOADING_CACHE.get(pattern).format(value);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return value.toString();
    }
}
